package com.atguigu.teach.mytask;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class MyResource{
    public synchronized void m1(){
        System.out.println(Thread.currentThread().getName()+"\t"+"----come in");
        //处理工作时间很长的话
       try {
                 TimeUnit.SECONDS.sleep(5);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }

    }
    Lock lock = new ReentrantLock();
    public void m2() throws InterruptedException {
//        if(lock.tryLock())
        if(lock.tryLock(3,TimeUnit.SECONDS)){

        try {
            System.out.println(Thread.currentThread().getName()+"\t"+"----come in");
            try {
                TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
        }finally {
          lock.unlock();
        }

        }else{
            System.out.println(Thread.currentThread().getName()+"\t"+"---- 抢锁失败");
        }
    }
}
public class MySyncVsReentrantLock {
    public static void main(String[] args) {
        MyResource myResource=new MyResource();
        new Thread(()->{try {
            myResource.m2();
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        },"t1").start();
        new Thread(()->{try {
            myResource.m2();
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        },"t2").start();
    }
}
